package concurrent;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 实战篇
 *
 * @author jack.wu
 * @since 2019/12/24 10:50
 */
public class ActualCombat {

    ExecutorService service = Executors.newFixedThreadPool(10);
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                                                            10,
                                                            60,
                                                            TimeUnit.SECONDS,
                                                            new ArrayBlockingQueue<>(10),
                                                            Executors.defaultThreadFactory(),
                                                            new ThreadPoolExecutor.AbortPolicy());

    /**
     * 获取商品基本信息
     *
     * @param goodsId 商品id
     * @return 商品详情
     * @throws InterruptedException
     */
    public String goodsDetailModel(long goodsId) throws InterruptedException {
        // 模拟查询商品详情200毫秒
        TimeUnit.MILLISECONDS.sleep(200);
        return "商品id：" + goodsId + "，商品基本信息。。。";
    }

    /**
     * 获取商品图片列表
     *
     * @param goodsId 商品id
     * @return 商品图片列表
     * @throws InterruptedException
     */
    public List<String> goodsImgsModelList(long goodsId) throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(200);
        return Arrays.asList("图1", "图2", "图3");
    }


    /**
     * 获取商品描述信息
     *
     * @param goodsId 商品id
     * @return 商品描述信息
     * @throws InterruptedException
     */
    public String goodsExtModel(long goodsId) throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(200);
        return "商品id：" + goodsId + "，商品描述信息。。。";
    }

    public Map<String, Object> goodsDetail(long goodsId) throws ExecutionException, InterruptedException {
        Map<String, Object> result = new HashMap<>(5);
        Future<String> goodsDetailModelFuture = service.submit(() -> goodsDetailModel(goodsId));
        Future<List<String>> goodsImgsFuture = service.submit(() -> goodsImgsModelList(goodsId));
        Future<String> goodsExtFuture = service.submit(() -> goodsExtModel(goodsId));
        result.put("goodsDetalModel", goodsDetailModelFuture.get());
        result.put("goodsImgsModel", goodsImgsFuture.get());
        result.put("goodsExtModel", goodsExtFuture.get());
        return result;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        long startTime = System.currentTimeMillis();
        Map<String, Object> result = new ActualCombat().goodsDetail(1L);
        System.out.println(result);
        System.out.println("耗时：" + (System.currentTimeMillis() - startTime));
    }

}
